package com.huanglejing.shanggou.fragment

import android.annotation.TargetApi
import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.activity.*
import com.huanglejing.shanggou.adapter.ProductImgsAdapter
import com.huanglejing.shanggou.bean.GoodsListBean
import com.huanglejing.shanggou.common.AppBaseFragment
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.GOODSLIST
import com.huanglejing.shanggou.interfaces.ProductImgsContract.ProductImgsPresenter
import com.huanglejing.shanggou.interfaces.ProductImgsContract.ProductImgsView
import com.huanglejing.shanggou.presenterimpl.ProductImgsImpl
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.rx.event.CompanyIdEvent
import com.huanglejing.shanggou.rx.event.JumpToHomeEvent
import com.huanglejing.shanggou.rx.rxbus.RxBus
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.CacheLoader
import com.huanglejing.shanggou.utils.UIHelper
import com.huanglejing.shanggou.utils.addTo
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import kotlinx.android.synthetic.main.fragment_product_imgs.*
import rx.Observable

/**
 * Created by Administrator on 2016/8/5 0005.
 */
class ProductImgsFragment : AppBaseFragment<ProductImgsPresenter<ProductImgsView>, ProductImgsView>(), ProductImgsView, XRecyclerView.LoadingListener {
    private var mAdapter: ProductImgsAdapter? = null
    private val XRview by lazy {
        rootViewWeakRef?.get()?.findViewById<XRecyclerView>(R.id.xr_product_imgs)
    }
    private val mEmptyView by lazy {
        rootViewWeakRef?.get()?.findViewById<View>(R.id.ll_xr_empty_error)
    }
    private val mErrorView by lazy {
        rootViewWeakRef?.get()?.findViewById<View>(R.id.ll_xr_error)
    }
  //  private var isShow = false;
    private val headerView by lazy {
        LayoutInflater.from(getActivity()).inflate(R.layout.layout_product_imgs_header, XRview, false)
    }
    var url = ""
    override var isShowLoading: Boolean = false

    init {
        containerId = R.id.fl_head_container
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        RxBus.get().toObservable(CompanyIdEvent::class.java)
                .doOnNext {
                    url = it?.url ?: ""
                    mBasePresenter?.getNetData()
                }.subscribe(SimpleSubscriber()).addTo(rxManager)
    }


    override fun createPresenter(): Any? = ProductImgsImpl()

    override fun getLayoutId(): Int = R.layout.fragment_product_imgs
    @TargetApi(14)
    override fun initWidget(rootView: View?) {
        iv_home_scan?.setOnClickListener {
            UIHelper.startActivity(SweepSearchActivity::class.java)
        }
        ll_search_container?.setOnClickListener {
            UIHelper.startActivity(SearchActivity::class.java)
        }
        iv_home_share?.setOnClickListener {
            ShareFragmentBar.newInstance().show(getActivity()?.supportFragmentManager, "ShareFragmentBar")
        }

//        this.toolbarLayout?.addView(Space(getActivity()).apply {
//            // layoutParams = ViewGroup.MarginLayoutParams(0, DisplayUtils.`$statusBarHeight`(viewContext) + DisplayUtils.`$toolbarHeight`(viewContext))
//            layoutParams = ViewGroup.MarginLayoutParams(0, `$statusBarHeight`(viewContext))
//        }, 0)
        XRview?.setLoadingListener(this@ProductImgsFragment)
        XRview?.setLoadingMoreProgressStyle(ProgressStyle.BallRotate)
        XRview?.setRefreshProgressStyle(ProgressStyle.BallRotate)

        val layoutManager = LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        XRview?.setLayoutManager(layoutManager);
        XRview?.addHeaderView(headerView)
        mAdapter = ProductImgsAdapter(getActivity(), GOODSLIST)
        XRview?.adapter = mAdapter

        initHeaderView()

    }

    private fun initHeaderView() {
        headerView?.findViewById<LinearLayout>(R.id.ll_newcom_pro_container)?.setOnClickListener {
            UIHelper.startActivity(NewComProActivity::class.java)
        }
        headerView?.findViewById<LinearLayout>(R.id.ll_recommend_container)?.setOnClickListener {
            UIHelper.startActivity(RecomendProActivity::class.java)
        }
        headerView?.findViewById<LinearLayout>(R.id.ll_promotion_container)?.setOnClickListener {
            UIHelper.startActivity(PromotionProActivity::class.java)
        }
        headerView?.findViewById<LinearLayout>(R.id.ll_history_container)?.setOnClickListener {
            UIHelper.startActivity(HistoryActivity::class.java)
        }

    }

//    override fun showLoading() {
//        if (isShow) {
//            super<ProductImgsView>.showLoading()
//        }
//    }

    override fun onResume() {
        super.onResume()
   //     isShow = true
        //layout_product_imgs_header
        //  mBasePresenter?.getNetData()
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
        }
        return Observable.just(map)
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (isVisibleToUser) {
           // isShow = true
            setIvExitVisible(false)

            Glide.with(this@ProductImgsFragment).load(url ?: "")
                    .placeholder(R.drawable.ic_img_error)
                    .error(R.drawable.ic_img_error)
                    .dontAnimate()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .fitCenter()
                    .thumbnail(0.1f)
                    .into(iv_home_img)

        } else {
         //   isShow = false
        }
        super.setUserVisibleHint(isVisibleToUser)
        isShowLoading = isVisibleToUser
    }

    override fun initData() {
    }

    override fun onStop() {
        super.onStop()
    }

    companion object {
        @JvmStatic
        fun newInstance(companyId: String): ProductImgsFragment {
            return ProductImgsFragment().apply {
            }
        }
    }

    override fun <T> showContent(data: T?) {
        try {
            val mNetData = data as? ArrayList<GoodsListBean>
            if (mNetData != null && GOODSLIST != null) {
                GOODSLIST?.clear()
                GOODSLIST?.addAll(mNetData)
                if (GOODSLIST?.size ?: 0 < 1 && mEmptyView!=null) {
                    XRview?.emptyView = mEmptyView
                    mEmptyView?.setOnClickListener {
                        RxBus.get().postEvent(JumpToHomeEvent())
                    }
                }
                CacheLoader.acache.put(C.Cache.GOODS_LIST, mNetData)
                mAdapter?.setData(GOODSLIST?.filter { it.level == 0 } as? ArrayList<GoodsListBean>
                        ?: arrayListOf())
                loadComPlete()
            }
        } catch (e: Exception) {
            KLog.e(e?.message)
        }

    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        GOODSLIST?.clear()
        if (mErrorView!=null){
            XRview?.emptyView = mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getNetData()
            }
        }
        mAdapter?.setData(arrayListOf())
        loadComPlete()
    }

    override fun onRefresh() {
        mBasePresenter?.getNetData()
        loadComPlete()
    }

    override fun onLoadMore() {
    }

    fun loadComPlete() {
        XRview?.loadMoreComplete()
        XRview?.refreshComplete()
        XRview?.setNoMore(true)

    }
}
